package com.itheima.tliaswebmanagement.controller;

import com.itheima.tliaswebmanagement.pojo.Emp;
import com.itheima.tliaswebmanagement.pojo.Result;
import com.itheima.tliaswebmanagement.service.EmpService;
import com.itheima.tliaswebmanagement.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {
    private final EmpService empService;

    @Autowired
    public LoginController(EmpService empService) {
        this.empService = empService;
    }

    /**
     * 接受并响应登录请求<br>
     * 登录成功后将返回jwt令牌，前端每次请求都会携带jwt令牌(键:token)，服务器以此判断用户是否已登录。
     *
     * @param emp Emp
     * @return Result
     */
    @PostMapping
    public Result login(@RequestBody Emp emp) {
        log.info("登录：{}", emp);
        emp = empService.selectByUsernameAndPassword(emp);
        if (emp != null) {
            Map<String, Object> claims = new HashMap<>();
            // 组织用户信息
            claims.put("id", emp.getId());
            claims.put("name", emp.getName());
            claims.put("username", emp.getUsername());
            // 生成jwt令牌
            String jwt = JwtUtils.generateJwt(claims);
            return Result.success(jwt);
        } else {
            return Result.error("账号或密码错误");
        }
    }
}
